package com.tiku.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.controller.DTO.ClearAnswerDTO;
import com.tiku.controller.DTO.QuestionLogDTO;
import com.tiku.entity.ChapterInfo;
import com.tiku.entity.ChapterSubInfo;
import com.tiku.entity.QuestionTable;
import com.tiku.entity.UserQuestionLog;
import com.tiku.mapper.ChapterInfoMapper;
import com.tiku.mapper.ChapterSubInfoMapper;
import com.tiku.service.QuestionTableService;
import com.tiku.service.UserQuestionLogService;
import com.tiku.mapper.UserQuestionLogMapper;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Date;
import java.util.Objects;

/**
 *
 */
@Service
public class UserQuestionLogServiceImpl extends ServiceImpl<UserQuestionLogMapper, UserQuestionLog>
    implements UserQuestionLogService{


    @Autowired
    private QuestionTableService questionTableService;

    @Autowired
    private UserQuestionLogMapper questionLogMapper;

    @Autowired
    private ChapterSubInfoMapper chapterSubInfoMapper;

    @Autowired
    private RedisCache redisCachel;

    @Autowired
    private ChapterInfoMapper chapterInfoMapper;
    @Override
    public ResultJson answerLog(QuestionLogDTO questionLogDTO) {
        String questionId = questionLogDTO.getQuestionId();
        QuestionTable questionInfo = questionTableService.getById(questionId);
        if (questionInfo == null){
            return ResultJson.error("题目ID错误");
        }
        String userAnswers = questionLogDTO.getAnswers();
        if (StringUtils.isEmpty(userAnswers)){
            return ResultJson.error("答案不能为空");
        }

        JSONArray jsons = JSON.parseArray(questionInfo.getAnswer());
        String userId = ThreadLocalUtil.getThreadLocal();
        UserQuestionLog userQuestionLog=new UserQuestionLog();
        userQuestionLog.setQuestionId(questionId);
        userQuestionLog.setUseranswer(userAnswers);
        userQuestionLog.setUserId(userId);
        userQuestionLog.setCreateTime(new Date());
        Integer rightFlag=1;
        for (int i = 0; i < jsons.size(); i++) {
            // 获取当前的 JSONObject
            JSONObject jsonObject = jsons.getJSONObject(i);
            // 检查 rightFlag 属性是否等于 1
            if (jsonObject.getInteger("rightFlag") != null && jsonObject.getInteger("rightFlag") == 1) {
                // 如果条件满足，将对象添加到 filteredArray
                if (!userAnswers.equals(jsonObject.getString("option"))) {
                    rightFlag=0;
                    break;
                }
            }
        }
        userQuestionLog.setRightflag(rightFlag);
        ChapterSubInfo chapterSubInfo = chapterSubInfoMapper.selectById(questionInfo.getChapterId());
        //记录最下级菜单
        String chapterIdText=questionInfo.getChapterId();
        String chapterIdTwo=questionInfo.getChapterId();
        String chapterId;
        String chapterName;
        userQuestionLog.setStem(questionInfo.getStem());

        while (true){
            ChapterSubInfo chapterSubInfo1 = chapterSubInfoMapper.selectById(chapterIdTwo);
            if (Objects.isNull(chapterSubInfo1)){


                break;
            }else {
                chapterIdTwo = chapterSubInfo1.getChapterId();

                chapterIdText=chapterIdTwo+chapterIdText;
            }

        }

        if (Objects.isNull(chapterSubInfo)){

            ChapterInfo chapterInfo = chapterInfoMapper.selectById(questionInfo.getChapterId());
            chapterId=chapterInfo.getId();
            chapterName=chapterInfo.getChapterName();
        }else {
            chapterId= chapterSubInfo.getChapterId();
            chapterName=chapterSubInfo.getChapterName();

        }
        userQuestionLog.setChapterInfoId(chapterId);
        userQuestionLog.setChapterName(chapterName);
        //暂时存储redis  每晚12点统一入库
        //key : questionLog: + 用户id + 类目ID+ 菜单ID+ 章节ID + 子章节ID + 题目ID


        redisCachel.setCacheObject("questionLog:"+userId+questionLogDTO.getSpecification()+questionLogDTO.getMenuId()+chapterIdText+questionId,userQuestionLog);


        return ResultJson.success();
    }

    @Override
    public ResultJson clearLog(ClearAnswerDTO clearAnswerDTO) {
        if (StringUtils.isEmpty(clearAnswerDTO.getSpecification())||StringUtils.isEmpty(clearAnswerDTO.getSubChapterId()) ){
            return ResultJson.error("参数异常");
        }
        String userId = ThreadLocalUtil.getThreadLocal();
        String subChapterId = clearAnswerDTO.getSubChapterId();
        ChapterSubInfo chapterSubInfo = chapterSubInfoMapper.selectById(subChapterId);
        if (Objects.isNull(chapterSubInfo)){
            return ResultJson.error("子章节ID错误");
        }
        String chapterId = chapterSubInfo.getChapterId();
        Collection<String> keys = redisCachel.keys("questionLog:" + userId + clearAnswerDTO.getSpecification() + chapterId + clearAnswerDTO.getSubChapterId() + "*");
        redisCachel.deleteObject(keys);
        redisCachel.deleteObject("question:"+userId+clearAnswerDTO.getSubChapterId());

        return ResultJson.success();
    }


}




